'''
UNIT INFO
Many often recurring functions are located here.
-centralize all special functions here
    -date-linked functions
    -file-linked etc.

ADAP FU
'''

##from apihelper import info
import sys
import webbrowser
import os
from datetime import datetime
from datetime import date
from datetime import timedelta
import shutil


# testvars
li = [4,6,7,4,8,1]
di = {'a':4,'b':8,'m':7, 'g':3,'f':2}
dili = di.items()
testdefdi =           {
            "labSource":["StaticText","Source",(10,5),(),0,["SET_FOCUS"]],
            "txtSource":["TextCtrl","",(50,5),(),1,["TEXT","TEXT_ENTER"],"TE_PROCESS_ENTER"],
            "labSubject":["StaticText","Subject",(160,5),(),2,["SET_FOCUS"]],
            "txtSubject":["TextCtrl","",(220,5),(300,21),3,["TEXT"]],
            "knopDruk":["Button","Drukken",(150,100),(),4,["BUTTON"]],
            "textHai":["TextCtrl","Hai",(30,50),(),5,["TEXT"]],
            "labelLab":["StaticText","labeltje",(250,50),(),6,["SET_FOCUS"]],
            "knopMega":["Button","Mega",(50,100),(),7,["BUTTON"]]
             }

hisli = ['almond', 'walter', 'joop', 'wim', 'piet', 'kees']
hisli = []

def prList(listli, ordered=True):
    '''Print a list of strings'''
    list(listli)
    if ordered: listli.sort()
    print "\n".join(listli )

def prDict (dictdi):
    '''Print a dictionary'''
    for tu in dictdi.items():
        print str(tu[0]) + ' - ' + str(tu[1])
    print '===================='

def sortItemsListByValue(itemsli):
    '''Sorts on the value of a  list of tuples.
    list: [('a', 4), ('b', 8), ('m', 7), ('g', 3), ('f', 2)]
    returns: [('f', 2), ('g', 3), ('a', 4), ('m', 7), ('b', 8)]
    '''

    firstli= []
    secli = []
    for elem in itemsli:
        elem = list(elem)
        elem.reverse()
        firstli.append(elem)
    firstli.sort()
    for elem in firstli:
        elem.reverse()
        elem = tuple(elem)
        secli.append(elem)
##    print secli
    return secli

def extractSortingDict(dictdi,colIndexit):
    '''Extract the key and a sorting-column from a dict of lists to
    form a new dict.
    {'key':[col1, col2, col3]} => {'key':col2}
    '''
    sortdi={}
    for elem in dictdi.items():
        sortdi[elem[0]]=elem[1][colIndexit]
##    print sortdi
    return sortdi

def buildSortedItemsList(dictdi,colIndexit):
    '''
    Build a sorted itemslist from a dictionary (of lists) with one column
    in the lists used as a sorting-index.
    '''
    sortdi = extractSortingDict(dictdi, colIndexit)
    sortli = sortItemsListByValue(sortdi.items())
    newli=[]
    for elem in sortli:
##        print elem
        itemli=[]
        itemli.append(elem[0])
        itemli.append(dictdi[elem[0]])
        itemtu = tuple(itemli)
        newli.append(itemtu)
##    print newli
    return newli

def updateHistoryList(historyli, newitemst, maxHistoLengthit=10):
    '''
    UI:
    Update history-list with new item while maintaining
    max length.
     '''

    if len(historyli) > maxHistoLengthit:
        historyli = historyli[:maxHistoLengthit]
    historyli.reverse()
    if newitemst in historyli:
        historyli.remove(newitemst)
    historyli.append(newitemst)
    if len(historyli) > maxHistoLengthit:
        historyli.remove(historyli[0])
    historyli.reverse()
##    print historyli
    return historyli

def openFile(filepathst):
    try:
        fsock = open(filepathst)
    except IOError:
        print "The file does not exist, exiting gracefully"
    return

def fileExistsOld(filepathst):
    # this creates the file if it dont exist, altering the state
    try:
        fsock = open(filepathst)
        fsock.close()
        return True
    except IOError:
        print "The file does not exist, exiting gracefully"
        return False

def fileExists(filepathst):
    
##    if os.path.isfile(filepathst):  # this  also creates a file if it dont exist, altering the state
    if os.path.exists(filepathst):
        print 'ja'
        return True
    else:
        print 'nee'
        return False
        

def openUrl(urlst):
    webbrowser.open(urlst)
    return

def info(object, spacing=10, collapse=1):
	"""
    Print methods and doc strings.
	Takes module, class, list, dictionary, or string.

	SEE ALSO THE HELP('OBJECT') FUNCTION OF PYDOC

	__author__ = "Mark Pilgrim (mark@diveintopython.org)"
    __version__ = "$Revision: 1.3 $"
    __date__ = "$Date: 2004/05/05 21:57:19 $"
    __copyright__ = "Copyright (c) 2001 Mark Pilgrim"
    __license__ = "Python"
    """

	methodList = [e for e in dir(object) if callable(getattr(object, e))]
	processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
	print "\n".join(["%s %s" %
					 (method.ljust(spacing),
					  processFunc(str(getattr(object, method).__doc__)))
					 for method in methodList])


def currentDate():
    '''
    returns like 2009-03-18
    '''
    return str(datetime.today())[:10]


def currentDateTime(usefilevalidformatbo = False):
    '''
    returns like 2009-03-18 14:27:31 if false
            like 2009-03-18-T142731 if True
    '''

    if usefilevalidformatbo:
        dtnow = datetime.now()
        datest = dtnow.strftime('%Y-%m-%d-T%H%M%S')
    else:
        rawdatest = str(datetime.now())
        datest = rawdatest[:19]
    return  datest

def dateFromIsoString(datest):
    # convert an isostring to a date-object
    dateli = datest.split('-')
    print dateli
    return date(int(dateli[0]),int(dateli[1]), int(dateli[2]))
 
def dateCountDelta(datetimest, incrementit):
    # count the iso-formated date(time) up or down (reckoning with month-borders)
    timepartest = ''
    # if length is 16 get date and short-time part
    if len(datetimest)==16:
        datepartest = datetimest[:10]
        timepartest = datetimest[len(datetimest)-5:]
    elif len(datetimest)==10:
        datepartest = datetimest
    dateob = dateFromIsoString(datepartest)
    print dateob
    deltaob = timedelta(days=incrementit)
    newdateob = dateob + deltaob
    newdatest = str(newdateob)
    
    if timepartest != '':
        newdatetimest = newdatest + ' ' + timepartest
    else:
        newdatetimest = newdatest
    
    return newdatetimest


def testStuff():
    x = str(sys.argv[0])
    y = os.path.basename(x)
    print x
    print y


def backupFile(filepathst, newfilerootst = ''):
    '''
    UNIT INFO
    -creates a copy of a file
    -use full path
    -returns string targetpath
    -optional
        -appends datestamp
        -or uses new fileroot-name

    ADAP FUT
    -generalize to module fileman.py
    '''

    print filepathst
    dirpathst = os.path.normpath(os.path.dirname(filepathst))
    filenamest = os.path.basename(filepathst)
    filerootst = os.path.splitext(filenamest)[0]
    fileextst = os.path.splitext(filenamest)[1]
    if newfilerootst <> '':
        dtnow = datetime.now()
        timeappendst = dtnow.strftime('%Y-%m-%d-T%H%M%S')
        targetrootst = newfilerootst + '_' + timeappendst
    else:
        timeappendst = str(datetime.now())[:10]
        targetrootst = filerootst + '_backup_' + timeappendst
    targetnamest = targetrootst + fileextst
    targetpathst = os.path.join(dirpathst, targetnamest )
    print targetpathst
    if os.path.isfile(filepathst):
        shutil.copyfile(filepathst, targetpathst )
    else: targetpathst = ''

    return targetpathst

def copyFile(sourcefilepathst, targetfrontreplacementst = '', targetappendst = '',
        targetappendtimebo = False, targetextensionreplacementst = ''):

    # only tested with non-null extenstion

    print sourcefilepathst
    dirpathst = os.path.normpath(os.path.dirname(sourcefilepathst))
    srcnamest = os.path.basename(sourcefilepathst)
    srcfrontst = os.path.splitext(srcnamest)[0]
    srcextst = os.path.splitext(srcnamest)[1]
    if targetfrontreplacementst <> '':
        tarfrontst = targetfrontreplacementst
    else:
        tarfrontst = srcfrontst
    tarfrontst = tarfrontst + targetappendst
    if targetappendtimebo:
        dtnow = datetime.now()
        timeappendst = dtnow.strftime('%Y-%m-%d-T%H%M%S')
        tarfrontst = tarfrontst + '_' + timeappendst

    if targetextensionreplacementst <> '':
        tarextst = '.' + targetextensionreplacementst
    else:
        tarextst = srcextst # includes a dot allready

    print tarfrontst
    print tarextst
    targetnamest = tarfrontst + tarextst

    targetpathst = os.path.join(dirpathst, targetnamest)
    print targetpathst
    if os.path.isfile(sourcefilepathst):
        shutil.copyfile(sourcefilepathst, targetpathst )
    else: targetpathst = ''

    return targetpathst


##def thisModuleDirPath():
##    '''
##    works only when called from this module itself!
##    '''
##    moduledirpathst = ''
##    modulefilepathst = str(sys.argv[0])
##    if os.path.basename(modulefilepathst) == 'jotools.py':
##        moduledirpathst = os.path.dirname(str(sys.argv[0]))
##    return moduledirpathst
##
##def thisModuleSubDir(subdirnamest):
##    return os.path.join(thisModuleDirPath(), subdirnamest)


if __name__ == '__main__':

    if fileExists('/home/joris/pd.txt'): 
        print 'ik besta'
    else:
        print 'ik ben er niet'

##    backupFile('C:/DoxLap/3temp/tijgerd/newfile.txt', 'secondfile')
##    os.startfile('c:/doxlap')
##    print currentDateTime()

##    copyFile('C:\\DoxLap\\1temp\\tmp\\RELATIONS.txt', 'newname','', True)
##    copyFile('C:\\DoxLap\\1temp\\tmp\\RELATIONS.txt', '','_upgraded_to_2.0', True, 'qlt')


##    print dateCountDelta("2012-08-30 20:15",  -1)
